package com.itheima.mp.Service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.Service.IUserService;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService{
    private final UserMapper userMapper;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deductMoneyById(Long id, Integer money) {
        //1.查询用户
        User user = getById(id);

        //2.校验用户状态
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常！");
        }

        //3.校验用户余额是否充足
        if (user.getBalance() < money) {
            throw new RuntimeException("用户余额不足！");
        }
        //4.扣减余额
        //userMapper.deductMoneyById(id,money);
        int remainMoney = user.getBalance() - money;
        lambdaUpdate().set(User::getBalance, remainMoney)
                .set(remainMoney == 0,User::getStatus, UserStatus.FROZEN)
                .eq(User::getId, id)
                .eq(User::getBalance,user.getBalance())//避免并发问题，当前更新时和查到的余额一致才做更新，相当于乐观锁
                .update();
    }

    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        return lambdaQuery().like(User::getUsername, name)
                .eq(User::getStatus, status)
                .gt(User::getBalance, minBalance)
                .lt(User::getBalance, maxBalance)
                .list();
    }

    @Override
    public UserVO queryUserAndAddressById(Long id) {
        //1.查询用户
        User user = userMapper.selectById(id);
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常 ！");
        }
        //2.查询地址
        List<Address> addresses = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, id)
                .list();
        //3.封装VO
        //3.1转User的PO为VO
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(user,userVO);
        if(CollUtil.isNotEmpty(addresses)){
            userVO.setAddresses(BeanUtil.copyToList(addresses, AddressVO.class));
        }
        return userVO;

    }

    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
        //1.查询用户
        List<User> users = listByIds(ids);
        if(CollUtil.isEmpty(users)){
            return Collections.emptyList();
        }

        //2.查询地址
        //2.1获取用户id集合
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        //2.2根据用户id查询地址
        List<Address> addresses  = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();
        //2.3转换地址VO
        List<AddressVO> addressVOS = BeanUtil.copyToList(addresses, AddressVO.class);
        //2.4用户地址集合纷纷组处理，相同用户的 放入一个集合（组）
        Map<Long,List<AddressVO>> userIdAddressesMap  = new HashMap<>();
        if(CollUtil.isNotEmpty(addresses)){
            userIdAddressesMap = addressVOS.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }
        //3.地址放到用户信息中
        List<UserVO> userVOS = new ArrayList<>();
        for (User user : users) {
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            userVO.setAddresses(userIdAddressesMap.get(user.getId()));
            userVOS.add(userVO);
        }
        return userVOS;
    }

    @Override
    public PageDTO<UserVO> queryUsersPage(UserQuery query){
        String name = query.getName();
        Integer status = query.getStatus();
        //1.构建分页条件

        Page<User> page = query.toMpPageDefaultSortByCreateTime();

        //2.分页查询
        Page<User> page1 = lambdaQuery()
                .like(name!=null,User::getUsername, name)
                .eq(status!=null,User::getStatus, status)
                .page(page);
        //3.封装VO结果
        return PageDTO.of(page1,user -> {
            //1.拷贝基础属性
            UserVO vo = BeanUtil.copyProperties(user,UserVO.class);
            //2.处理特殊逻辑
            vo.setUsername(vo.getUsername().substring(0,vo.getUsername().length()-2)+"**");
            return vo;
        });
    }
}
